package com.fanbuchi.fukua.manager;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import com.fanbuchi.fukua.application.SuperApp;
import com.fanbuchi.fukua.entity.OauthEntity;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.io.IOException;

/**
 * Created by Administrator on 2015/7/10.
 */
public final class OauthManager {
    private static OauthEntity oauthEntity;

    public final static OauthEntity getOauthEntity() {
        if (oauthEntity==null){
            SharedPreferences sharedPreferences=SuperApp.getApplication().getSharedPreferences("oauth2", Context.MODE_PRIVATE);
            String oauth2=sharedPreferences.getString("oauth2",null);
            if (TextUtils.isEmpty(oauth2)||oauth2.length()<=0){
                return null;
            }
            try {
                oauthEntity=SuperApp.getMapper().readValue(oauth2,OauthEntity.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return oauthEntity;
    }

    public final  static void setOauthEntity(OauthEntity oauthEntity) {
        OauthManager.oauthEntity=oauthEntity;
        SharedPreferences sharedPreferences=SuperApp.getApplication().getSharedPreferences("oauth2", Context.MODE_PRIVATE);
        if (oauthEntity==null){
            sharedPreferences.edit().clear().commit();
            return;
        }

        String oauth2=null;
        try {
             oauth2=SuperApp.getMapper().writeValueAsString(OauthManager.oauthEntity);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        sharedPreferences.edit().putString("oauth2",oauth2).commit();
    }


    public final static String getRefreshToken() {
        return getOauthEntity()==null?null:getOauthEntity().getRefreshToken();
    }
}
